package com.ruoyi.live.websocket;

import cn.hutool.core.util.RandomUtil;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

@Component
@ServerEndpoint("/chat")
public class ChatChannel {

    //选择线程安全的集合
    private static List<Session> sessions = new CopyOnWriteArrayList<>();

    @OnOpen
    public void onOpen(Session session) throws IOException {
        System.out.println("有新客户端建立链接。。。。");
        sessions.add(session);

        //利用随机数生成游客昵称
        String name = "游客"+RandomUtil.randomNumbers(6);

        Map<String, Object> userProperties = session.getUserProperties();
        userProperties.put("name", name);

        for (Session session1 : sessions) {
            session1.getBasicRemote().sendText("欢迎["+name+"]进入直播间，当前在线："+sessions.size()+"人");
        }


    }

    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        System.out.println("有客户端发送消息。。。。");

        String name = (String) session.getUserProperties().get("name");

        for (Session userSession : sessions) {
            userSession.getBasicRemote().sendText(name+":"+message);
        }

    }

    @OnClose
    public void onClose(Session session, CloseReason reason) throws IOException {
        System.out.println("有客户端断开连接。。。。");
        sessions.remove(session);

        String name = (String) session.getUserProperties().get("name");

        for (Session session1 : sessions) {
            session1.getBasicRemote().sendText("用户["+name+"]退出直播间，当前在线："+sessions.size()+"人");
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("有客户端发生异常。。。。");

    }


}
